package com.magupe.push.server.handler;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.magupe.push.common.protocol.request.MessageRequestPacket;
import com.magupe.push.common.protocol.request.RPCMessageRequestPacket;
import com.magupe.push.common.protocol.response.MessageResponsePacket;
import com.magupe.push.common.protocol.response.RPCMessageResponsePacket;
import com.magupe.push.log.util.LogUtils;
import com.magupe.push.rpc.RPCClient;
import com.magupe.push.rpc.service.MessageService;
import com.magupe.push.server.utils.AuthenticationSessionUtil;
import com.magupe.push.server.utils.MapperUtils;
import com.magupe.push.server.utils.SessionUtil;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket>{

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	
	@Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket packet) {
		/**
		 * 查看数据包是否是有效数据发送方的channel发送的
		 */
		Channel channel = AuthenticationSessionUtil.getChannel(packet.getSecret());
        if(channel != null && AuthenticationSessionUtil.hasAuthentication(channel)) {
        	MessageResponsePacket response = new MessageResponsePacket();
        	response.setSuccess(true);
        	response.setMessage("ok");
        	response.setMsgId(packet.getMsgId());
        	response.setSource(packet.getSource());
        	response.setUserId(packet.getUserId());
        	response.setContentId(packet.getContentId());
        	response.setSecret(packet.getSecret());
        	
        	/**
        	 * 获取移动端用户的channel，并验证其是否有效
        	 */
        	String userId = packet.getUserId();
        	Channel userChannel = SessionUtil.getChannel(userId);
        	
        	//userChannel = null;
        	
        	MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        	if(userChannel != null && SessionUtil.hasLogin(userChannel)) {
            	/**
            	 * 发送消息到clientsdk端（移动端），通知clientsdk端有消息
            	 */
            	messageResponsePacket.setSuccess(true);
            	messageResponsePacket.setMessage(packet.getMessage());
            	messageResponsePacket.setUserId(packet.getUserId());
            	messageResponsePacket.setSource(packet.getSource());
            	messageResponsePacket.setContentId(packet.getContentId());
            	messageResponsePacket.setSecret(packet.getSecret());
            	messageResponsePacket.setMsgId(packet.getMsgId());
            	messageResponsePacket.setVersion(packet.getVersion());
            	userChannel.writeAndFlush(messageResponsePacket);
            	
            	LogUtils.processLog(ctx.channel(), packet, "正常推送消息", false, null);
            	
            	// 发送消息到client端，通知client端消息发送成功
            	channel.writeAndFlush(response);
        	} 
        	
        	if(userChannel == null) {
        		String mapper = MapperUtils.getMapper(userId);
        		mapper = mapper.replace("/", "");
        		String host = mapper.split(":")[0];
        		String port = mapper.split(":")[1];
        		
        		RPCMessageRequestPacket rpcMessageRequestPacket = new RPCMessageRequestPacket();
        		rpcMessageRequestPacket.setMessage(packet.getMessage());
        		rpcMessageRequestPacket.setSecret(packet.getSecret());
        		rpcMessageRequestPacket.setContentId(packet.getContentId());
        		rpcMessageRequestPacket.setUserId(packet.getUserId());
        		rpcMessageRequestPacket.setSource("rpc");
        		rpcMessageRequestPacket.setMsgId(packet.getMsgId());
        		rpcMessageRequestPacket.setVersion(packet.getVersion());
        		
        		executor.submit(new Runnable() {
					@Override
					public void run() {
		        		RPCClient client = new RPCClient(host, port);
		        		MessageService messageService = client.createProxy(MessageService.class);
		        		RPCMessageResponsePacket result = messageService.sendMessage(rpcMessageRequestPacket);
		        		
		        		LogUtils.processLog(ctx.channel(), result, "转发推送消息成功", false, null);
		        		
		        		// 发送消息到client端，通知client端消息发送成功
		            	response.setMessage("rpc ok");
		            	response.setSource(result.getSource());
		            	channel.writeAndFlush(response);
					}
        		});
        	}			
        } 
    }
}